<?php if(!defined('BASEPATH')) exit('No direct script access allowed.');
    class Backend extends CI_Controller
    {
        /**
         * list table has 'key' that corresponding to the tables of database
         * 'value' option 
        */
        private $list_table = array(
                        'tblproduct_category' => 'Product category',
                        'tblproduct' => 'Product',
                        'tblnews_category' => 'News category',
                        'tblnews' => 'News',
                        'tblorder' => 'Order',
                        'tblcontact' => 'Infomation contact'
                        );
        
        /**
         * list table has 'key' that corresponding to the tables of database
         * 'value' option (for panel)
        */
        private $list_table_panel = array(
                        'tblinfo_company' => 'Infomation Company'
                        );
        
        /**
         *  title for each table (section view)
        */
        private $columns_title=array(
                    'tblproduct_category' => array(
                                        'id'=>'ID',
                                        'name'=>'Name',
                                        'sort'=>'Sort',
                                        'parentid'=>'Parent ID',
                                        'ispublish'=>'Publish'
                                    ),
                     'tblproduct' => array(
                                        'id'=>'ID',
                                        'name'=>'Name',
                                        'categoryid'=>'Category ID',
                                        'image'=>'Image',
                                        'price' =>'Price',
                                        'price_promotion'=>'Price promotion',
                                        'sort'=>'Sort',
                                        'volume_exists'=>'Volume exists',
                                        'sold' => 'Sold',
                                        'ispublish'=>'Publish'
                                    ),
                     'tblnews_category' => array(
                                        'id'=>'ID',
                                        'name'=>'Name',
                                        'sort'=>'Sort',
                                        'parentid'=>'Parent ID',
                                        'ispublish'=>'Publish'
                                    ),
                     'tblnews' => array(
                                        'id'=>'ID',
                                        'title'=>'Title',
                                        'categoryid'=>'Category ID',
                                        'image'=>'Image',
                                        'sort'=>'Sort',
                                        'summary'=>'Summary',
                                        'ispublish'=>'Publish'
                                    ),
                     'tblorder' => array(
                                        'id'=>'ID',
                                        'email'=>'Email',
                                        'fullname'=>'Fullname',
                                        'phone'=>'Phone',
                                        'address'=>'Address',
                                        'city'=>'City',
                                        'payment_form'=>'Payment Form',
                                        //'shipping_form'=>'Shipping Form',
                                        'total_payment'=>'Total Payment',
                                        //'detail_payment'=>'Detail Payment',
                                        //'message_customer'=>'Message Customer',
                                        'creator'=>'Creator',
                                        'date_create'=>'Date create',
                                        'iscompleted'=>'Completed'
                                    ),
                     'tblcontact' => array(
                                        'id'=>'ID',
                                        'fullname'=>'Full Name',
                                        'address'=>'Address',
                                        'phone'=>'Phone',
                                        'email' =>'Email',
                                        'title'=>'Title',
                                        'content'=>'Content',
                                        'status'=>'Status',
                                        'email_receive_require' => 'Email receive require'
                                    )                   
        );
        
        /**
         *   list page size (section view)
        */ 
        private $page_size=array(
            'tblproduct_category'=>10,
            'tblproduct'=>15,
            'tblnews_category'=>10,
            'tblnews'=>15,
            'tblorder'=>20
        );
        
        /**
         *  field label for each table (section insert) 
        */
        private $list_label=array(
                    'tblproduct_category' => array(
                                        'id'=>'ID',
                                        'meta_keywords'=>'Meta keywords',
                                        'meta_description'=>'Meta description',
                                        'name'=>'Name',
                                        'alias'=>'Alias',
                                        'sort'=>'Sort',
                                        'parentid'=>'Parent ID',
                                        'ispublish'=>'Publish',
                                        //'isdelete'=>'Delete'
                                    ),
                      'tblproduct' => array(
                                    'id'=>'ID',
                                    'meta_keywords'=>'Meta keywords',
                                    'meta_description'=>'Meta description',
                                    'name'=>'Name',
                                    'alias'=>'Alias',
                                    'categoryid'=>'Category ID',
                                    'image'=>'Image',
                                    'price' =>'Price',
                                    'price_promotion'=>'Price promotion',
                                    'sort'=>'Sort',
                                    'volume_exists'=>'Volume exists',
                                    'sold' => 'Sold',
                                    'description'=>'Description',
                                    'ispublish'=>'Publish'
                                ),
                      'tblnews_category' => array(
                                        'id'=>'ID',
                                        'meta_keywords'=>'Meta keywords',
                                        'meta_description'=>'Meta description',
                                        'name'=>'Name',
                                        'alias'=>'Alias',
                                        'sort'=>'Sort',
                                        'parentid'=>'Parent ID',
                                        'ispublish'=>'Publish',
                                        //'isdelete'=>'Delete'
                                    ),
                      'tblnews' => array(
                                    'id'=>'ID',
                                    'meta_keywords'=>'Meta keywords',
                                    'meta_description'=>'Meta description',
                                    'title'=>'Title',
                                    'alias'=>'Alias',
                                    'categoryid'=>'Category ID',
                                    'image'=>'Image',
                                    'sort'=>'Sort',
                                    'summary'=>'Summary',
                                    'content_news' => 'Content',
                                    'ispublish'=>'Publish'
                                ),
                       'tblorder' => array(
                                        'id'=>'ID',
                                        'email'=>'Email',
                                        'fullname'=>'Fullname',
                                        'phone'=>'Phone',
                                        'address'=>'Address',
                                        'city'=>'City',
                                        'payment_form'=>'Payment Form',
                                        'shipping_form'=>'Shipping Form',
                                        'total_payment'=>'Total Payment',
                                        'detail_payment'=>'Detail Payment',
                                        'message_customer'=>'Message Customer',
                                        'creator'=>'Creator',
                                        'date_create'=>'Date create',
                                        //'iscompleted'=>'Completed'
                                    ),
                       'tblinfo_company' => array(
                                    'id'=>'ID',
                                    'companyname'=>'Company Name',
                                    'imagelogo'=>'Logo',
                                    'slogan'=>'Slogan',
                                    'address'=>'Address',
                                    'phone'=>'Phone',
                                    'cell_phone'=>'Mobile',
                                    'email'=>'Email',
                                    'fax'=>'Fax',
                                    'website'=>'Website',
                                    'introduction'=>'Introduction'
                                )
        );
        
        /**
         *  list field of table that show textarea (section insert) 
         *  $value is number row
        */
        private $list_textarea=array(
                        'tblproduct_category' => array(
                                            'meta_description'=>'2'
                                        ),
                        'tblproduct' => array(
                                            'meta_description'=>'2'
                                        ),
                        'tblnews_category' => array(
                                            'meta_description'=>'2'
                                        ),
                        'tblnews' => array(
                                            'meta_description'=>'2',
                                            'summary'=>'3'
                                        ),
                        'tblorder' => array(
                                            'shipping_form'=>'2',
                                            'message_customer'=>'2'
                                        ),
                        'tblinfo_company' => array(
                                            'slogan'=>'2'
                                        )               
        );
        
        /**
         *  list field of table that using ckeditor (section insert) 
         *  $value is height
        */
        private $list_ckeditor=array(
                        'tblproduct' => array(
                                            'description'=>'250px'
                                        ),
                        'tblinfo_company' => array(
                                            'introduction'=>'250px'
                                        ),
                        'tblnews' => array(
                                            'content_news'=>'250px'
                                        ),
                        'tblorder' => array(
                                            'detail_payment'=>'250px'
                                        )
                        
        );
        
        /**
         *  list field of table that show dropdown list (section insert) 
         *  $k => $v ($k: foreign key, $v: table associate)
        */
        private $list_dropdown=array(
                        'tblproduct_category' => array(
                                            'parentid'=>'tblproduct_category'
                                        ),
                        'tblproduct' => array(
                                            'categoryid'=>'tblproduct_category'
                                        ),
                        'tblnews_category' => array(
                                            'parentid'=>'tblnews_category'
                                        ),
                        'tblnews' => array(
                                            'categoryid'=>'tblnews_category'
                                        ),
        );
        
        function _get_data_for_dropdown_list($table)
        {
             $this->load->model('dashboard/backend_model','be');
             //get level 0
             $result=array();
             foreach($this->be->get_data_table_by_parentid($table,0) as $item)
             {
                $level='-';
                if(isset($item['name']))
                {
                    $item['name']=$level.$item['name'];
                }
                else if(isset($item['title']))
                {
                    $item['title']=$level.$item['title'];
                }
                $result[]= $item;
                $this->_get_sub_category($table,$item['id'],$result,$level.'--');
             }
             //print_r($result);
             return $result;
        }
        
        function _get_sub_category($table,$parentid,&$result,$level)
        {
             $this->load->model('dashboard/backend_model','be');
             foreach($this->be->get_data_table_by_parentid($table,$parentid) as $sub_item)
             {
                if(isset($sub_item['name']))
                {
                   $sub_item['name']=$level.$sub_item['name'];
                }
                else if(isset($sub_item['title']))
                {
                   $sub_item['title']=$level.$sub_item['title'];
                }
                $result[]=$sub_item;
                $this->_get_sub_category($table,$sub_item['id'],$result,$level.'---');
             }
        }
        
        function __construct()
        {
            parent::__construct();
            $this->load->helper(array('form','url'));       
            $this->load->library('session');
            
            if($this->session->userdata('islogged')== TRUE && $this->session->userdata('username')!='')
            {
                if($this->session->userdata('roles')!='admin')
                {
                     redirect('dashboard/login');
                }   
            }   
            else
            {
                redirect('dashboard/login');
            }
        }
        
        function index()
        {
            $this->_load_site(null,null);
        }
        
        /**
         * load site with parameter $action
         * $action==null, load site default
         * $action==insert, load site insert
         * $action==view, load site view
        */
        function _load_site($action=null,$content=null)
        {
            $data=array(
                    'list_table'=>$this->list_table,
                    'action'=> $action,
                    'content' => $content
                    );         
            $this->load->view('dashboard/manager',$data);
        }
        
        function insert($table,$data_field=null,$upload=null)
        {
            $title = isset($this->list_table[$table])?$this->list_table[$table]:$this->list_table_panel[$table];
            $content=array(
                        'title'=> $title,
                        'table'=> $table
            );
            //get status panel area of table
            isset($this->list_table_panel[$table])?$content['is_panel_area']=TRUE:$content['is_panel_area']=FALSE;
            //get list label
            if(isset($this->list_label[$table]))
            {
                $content['list_label']=$this->list_label[$table];
            }
            //get list field that show textarea
            if(isset($this->list_textarea[$table]))
            {
                $content['list_textarea']=$this->list_textarea[$table];
            }
            //get list field that show dropdown list
            if(isset($this->list_dropdown[$table]))
            {
                foreach($this->list_dropdown[$table] as $foreign_key => $parent_table)
                {
                    $content['list_dropdown'][$foreign_key]=$this->_get_data_for_dropdown_list($parent_table);
                }
            }
            //print_r($data_field);
            //get data field for update
            $content['data_field']=$data_field;
            //data upload
            $content['upload']=$upload;
            
            //get list field that using ckeditor
            if(isset($this->list_ckeditor[$table]))
            {
                //initialization ckeditor 4.1.1
                $this->load->helper('ckeditor');
                foreach($this->list_ckeditor[$table] as $field => $height)
                {
                    //Ckeditor's configuration
            		$content['ckeditor'][$field] = array(
            			//ID of the textarea that will be replaced
            			'id' 	=> 	$field,
            			'path'	=>	'js/ckeditor',
            			//Optionnal values
            			'config' => array(
            				'toolbar' 	=> 	"Full", 	//Using the Full toolbar
            				'width' 	=> 	"100%",	//Setting a custom width
            				'height' 	=> 	$height,	//Setting a custom height
                            //'toolbar' 	=> 	array(	//Setting a custom toolbar
                             //   					array('Bold', 'Italic','Underline'),
                            //    					array('Underline', 'Strike', 'FontSize'),
                            //    					array('Smiley','Image'),
                            //    					'/'
                            //    				)
            			),
            			//Replacing styles from the "Styles tool"
            			'styles' => array(
            				//Creating a new style named "style 1"
            				'style 1' => array (
            					'name' 		=> 	'Blue Title',
            					'element' 	=> 	'h2',
            					'styles' => array(
            						'color' 	=> 	'Blue',
            						'font-weight' 	=> 	'bold'
            					)
            				),
            				//Creating a new style named "style 2"
            				'style 2' => array (
            					'name' 	=> 	'Red Title',
            					'element' 	=> 	'h2',
            					'styles' => array(
            						'color' 		=> 	'Red',
            						'font-weight' 		=> 	'bold',
            						'text-decoration'	=> 	'underline'
            					)
            				)
            			)
            		);
                }
            }
            
            $this->_load_site('insert',$content);
        }
        
        function view($table)
        {
            $content=array(
                        'title'=>$this->list_table[$table],
                        'table'=>$table
            );
            //get title
            if(isset($this->columns_title[$table]))
            {
                $content['columns_title']=$this->columns_title[$table];
            }
            //get page_size
            if(isset($this->page_size[$table]))
            {
                $content['page_size']=$this->page_size[$table];
            }
            $this->_load_site('view',$content);
        }
        
        function edit($table,$id)
        {
            $this->load->model('dashboard/backend_model','be');
            $data_field=$this->be->get_data_table_by_id($table,$id);
            $this->insert($table,$data_field);
        }
        
        function change_status($table,$id,$field,$status)
        {
            $this->load->model('dashboard/backend_model','be');
            $this->be->change_status($table,$id,$field,$status);
            $this->view($table);
            redirect('dashboard/backend/view/'.$table);
        }
        
        function delete_record($table,$id)
        {
            $this->load->model('dashboard/backend_model','be');
            $this->be->delete_record($table,$id);
            redirect('dashboard/backend/view/'.$table);
        }
        
        function process_insert_update($table)
        {
            if($_POST['submit']=='Insert' || $_POST['submit']=='Update')
            {
                $list_field = null;
                foreach($_POST as $field => $value)
                {
                    //echo "$field=$value<br />";
                    if($field != 'submit') //ignore value of submit button
                    {
                        $list_field[$field]=trim($value);
                    }
                }
                //echo print_r($list_field);
                //set alias
                if(isset($list_field['alias']))
                {
                    $this->load->helper('common_function'); 
                    if(isset($list_field['name']))
                    {
                        $list_field['alias']= strtolower(standardize_url($list_field['name']));  
                    }
                    else if(isset($list_field['title']))
                    {
                        $list_field['alias']= strtolower(standardize_url($list_field['title']));   
                    }
                }
               
                //process image upload
                $config['upload_path']='./data/images/';
                $config['allowed_types']='gif|jpg|png|jpeg';
                $config['max_size']='2048'; //kb
                $config['max_width']='0';
                $config['max_height']='0';
                
                $this->load->library('upload',$config);
                
                if( ! $this->upload->do_upload())
                {
                    //$upload=array('error' => $this->upload->display_errors());
                    //$this->insert($table,null,$upload);
                    //print_r($upload);
                }
                else //upload success
                {
                    $upload = array('upload_data' => $this->upload->data());
                    //$this->insert($table,null,$upload);
                    //print_r($upload);
                    $list_field['image']=$upload['upload_data']['file_name'];
                }
                
                if($_POST['submit']=='Insert')
                {
                    //insert
                    $this->load->model('dashboard/backend_model','be');
                    $this->be->insert_data_into_table($table,$list_field);
                    redirect('dashboard/backend/view/'.$table);
                }
                else
                {
                    //update
                    $this->load->model('dashboard/backend_model','be');
                    $this->be->update_data_into_table($table,$list_field);
                    if(isset($this->list_table_panel[$table]))
                    {
                         redirect('dashboard/backend');
                    }
                    else
                    {
                         redirect('dashboard/backend/view/'.$table);
                    }
                }
            } 
        }
    }
?>